package com.hzhr.iot.login.dao;

import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.login.entity.UserCardEntity;
import com.hzhr.iot.login.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Repository
public class UserCardDao {
    @Autowired
    RedisUtil redisUtil;

    public int insert(UserCardEntity entity) {
        String token = entity.getToken();
        String key = "user_service:USER_CARD:" + token;

        redisUtil.hmSet(key, "userId", entity.getUserId().toString());
        redisUtil.hmSet(key, "userName", entity.getUserName());
        redisUtil.hmSet(key, "userCode", entity.getUserCode());
        redisUtil.hmSet(key, "companyId", entity.getCompanyId().toString());
        redisUtil.hmSet(key, "deptId", entity.getDeptId().toString());
        redisUtil.hmSet(key, "type", entity.getType());
        Date currentDate = new Date();
        redisUtil.hmSet(key, "expireTime", HzhrTypeUtil.long2string(entity.getExpireTime()));
        long expiredTime = (entity.getExpireTime() - currentDate.getTime()) / 1000 / 60;
        redisUtil.expired(key, expiredTime, TimeUnit.MINUTES);

        entity.setToken(token);
        return 1;
    }

    public int delete(String token) {
        String key = "user_service:USER_CARD:" + token;
        redisUtil.remove(key);
        return 1;
    }

    public UserCardEntity selectByToken(String token) {
        if (StringUtils.isEmpty(token)) return null;
        Map<Object, Object> tokenMap = redisUtil.hmGetAll("user_service:USER_CARD:" + token);
        if (tokenMap == null || tokenMap.size() == 0) return null;

        UserCardEntity userCardEntity = new UserCardEntity();
        userCardEntity.setToken(token);
        userCardEntity.setUserId(HzhrTypeUtil.object2integer(tokenMap.get("userId")));
        userCardEntity.setUserCode(HzhrTypeUtil.object2string(tokenMap.get("userCode")));
        userCardEntity.setUserName(HzhrTypeUtil.object2string(tokenMap.get("userName")));
        userCardEntity.setCompanyId(HzhrTypeUtil.object2integer(tokenMap.get("companyId")));
        userCardEntity.setDeptId(HzhrTypeUtil.object2integer(tokenMap.get("deptId")));
        userCardEntity.setExpireTime(HzhrTypeUtil.object2long(tokenMap.get("expireTime")));
        userCardEntity.setType(HzhrTypeUtil.object2string(tokenMap.get("type")));

        return userCardEntity;
    }
}
